﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

using VTV.TaskManagementSystem.Common;

namespace VTV.TaskManagementSystem.BusinessLogic
{
    public class User
    {
        public string ErrorMessage { get; set; }

        private DataAccess.User _dataAccess;

        private readonly Regex _usernameRegex = new Regex("");

        public bool CheckLogin(string username, string password, out Entities.Login user)
        {
            try
            {
                string md5Password;
                if (!Validation(username, password, out md5Password))
                {
                    user = null;
                    return false;
                }

                _dataAccess = new DataAccess.User();
                var result = _dataAccess.CheckLogin(username.ToLower(), md5Password, out user);
                this.ErrorMessage = (!result) ? _dataAccess.ErrorMessage : null;
                return result;
            }
            catch (Exception e)
            {
                ErrorMessage = e.Message;
                user = null;
                return false;
            }
        }

        private bool Validation(string username, string password, out string md5Password)
        {
            try
            {
                if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password) && _usernameRegex.IsMatch(username))
                {
                    md5Password = password.ToMD5();
                    if (String.IsNullOrEmpty(md5Password))
                    {
                        return false;
                    }

                    return true;
                }

                md5Password = null;
                return false;
            }
            catch
            {
                md5Password = null;
                return false;
            }
        }
    }
}
